﻿using MugenMvvmToolkit.Interfaces;
using MugenMvvmToolkit.Utils;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;

namespace MugenMvvmToolkit
{
    /// <summary>
    ///     Represents the base class for Mvvm application.
    /// </summary>
    public abstract class MvvmApplication : Application
    {
        #region Fields

        private static IBootstrapper _bootstrapper;

        #endregion

        #region Constructors

        /// <summary>
        ///     Initializes a new instance of the MvvmApplication class.
        /// </summary>
        protected MvvmApplication()
        {
            Suspending += OnSuspending;
        }

        #endregion

        #region Properties

        /// <summary>
        ///     Gets the <see cref="IBootstrapper" /> for the current <see cref="MvvmApplication" />.
        /// </summary>
        public static IBootstrapper Bootstrapper
        {
            get { return _bootstrapper; }
            private set
            {
                Should.PropertyBeNotNull(value, "Bootstrapper");
                _bootstrapper = value;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        ///     Invoked when the application is launched normally by the end user.  Other entry points
        ///     will be used when the application is launched to open a specific file, to display
        ///     search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Bootstrapper = GetBootstrapper();
            if (!Bootstrapper.IsStarted)
                Bootstrapper.Start();
        }

        /// <summary>
        ///     Invoked when application execution is being suspended.  Application state is saved
        ///     without knowing whether the application will be terminated or resumed with the contents
        ///     of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="suspendingEventArgs">Details about the suspend request.</param>
        protected virtual void OnSuspending(object sender, SuspendingEventArgs suspendingEventArgs)
        {
            if (Bootstrapper != null)
                Bootstrapper.Stop();
        }

        /// <summary>
        ///     Gets the <see cref="IBootstrapper" /> for the current <see cref="MvvmApplication" />.
        /// </summary>
        /// <returns>
        ///     An instance of <see cref="IBootstrapper" />.
        /// </returns>
        protected abstract IBootstrapper GetBootstrapper();

        #endregion
    }
}